﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using LorraineSec.DatabaseLib;

namespace LorraineSec.DatabaseLib.DataObjects
{
    public class Usergroup
    {
        #region Constants
        private const string ROOT_STR = XmlDatabase.USERGROUP;
        private const string ID_STR = XmlDatabase.ID;
        private const string NAME_STR = XmlDatabase.NAME;
        #endregion

        private XmlNode xmlGroupRoot;
        private XmlNode xmlName;
        

        public Usergroup(XmlNode node)
        {
            xmlGroupRoot = node;
            xmlName = xmlGroupRoot.SelectSingleNode(NAME_STR);
        }

        public static List<Usergroup> GetList(XmlDatabase db)
        {
            List<Usergroup> retList = new List<Usergroup>();
            if (db.usergroups != null)
            {
                XmlNodeList nodeList = db.usergroups.SelectNodes(ROOT_STR);
                retList.Capacity = nodeList.Count;
                foreach (XmlNode n in nodeList)
                {
                    retList.Add(new Usergroup(n));
                }
            }
            return retList;
        }

        public static implicit operator Usergroup(XmlNode node)
        {
            return new Usergroup(node);
        }

        public static explicit operator XmlNode(Usergroup u)
        {
            return u.xmlGroupRoot;
        }

        public uint ID
        {
            get { return UInt32.Parse(xmlGroupRoot.Attributes[ID_STR].Value); }
        }

        public string Name
        {
            get { return xmlName.InnerText; }
            set { xmlName.InnerText = value; }
        }

        public List<Compartment> GetCompartments(XmlDatabase db)
        {
            List<Compartment> list = db.getCompartmentsForUsergroup((int)ID);
            if (list == null)
                return new List<Compartment>();
            else
                return list;
        }

        public void SetCompartments(XmlDatabase db, List<Compartment> list)
        {
            db.removeUgToCompByUsergroupId((int)ID);
            foreach (Compartment cmp in list)
            {
                db.addUsergroupToCompartmentRelation((int)ID, (int)cmp.ID);
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}
